<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择日期" prop="date">
        <el-date-picker clearable v-model="dateTime" style="width:335px" type="datetimerange" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择创建时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="发送人" prop="messageSender" v-show="this.activeName === 'first'">
        <el-input v-model="queryParams.messageSender" placeholder="请输入发送人" clearable />
      </el-form-item>
      <el-form-item label="接收人" prop="messageReciver" v-show="this.activeName === 'second'">
        <el-input v-model="queryParams.messageReciver" placeholder="请输入发送人" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="接收列表" name="first"></el-tab-pane>
      <el-tab-pane label="发送列表" name="second"></el-tab-pane>
    </el-tabs>

    <el-row :gutter="10" class="mb8" v-show="this.activeName === 'second'">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
      <el-table-column prop="index" label="序号" width="55" align="center"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="接收人" align="center" prop="messageReciver">
        <template slot-scope="scope">
          {{ scope.row.messageReciver === 'ALL' ? '全体用户' : scope.row.messageReciver }}
        </template>
      </el-table-column>
      <el-table-column label="消息" align="center" prop="message" width="600" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status === "0" ? '未读' : scope.row.status === "1" ? '已读' : '公告' }}
        </template>
      </el-table-column>
      <el-table-column label="发送人" align="center" prop="messageSender" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-show="activeName === 'second'" :disabled="scope.row.status==='1'">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" :disabled="scope.row.status==='0'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改公告通知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :show-close="false"
    :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable v-model="createTime" :disabled="true" style="width:380px" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择创建时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="接收人" prop="messageReciver">
          <el-input v-model="form.messageReciver" placeholder="请输入接收人" :disabled="ReciverDisabled" clearable />
        </el-form-item>
        <el-form-item label="消息" prop="message">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入消息" v-model="form.message">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMessage, getMessage, delMessage, addMessage, updateMessage } from "@/api/system/message";

export default {
  name: "Message",
  data() {
    return {
      activeName: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告通知表格数据
      messageList: [],
      dateTime: [this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1, 0, 0, 0, 0)), this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 23, 59, 59, 999))],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        messageReciver: '',
        startTime: "",
        endTime: "",
        message: null,
        status: null,
        messageSender: null,
        readTime: null,
        detailId: null
      },
      // 表单参数
      form: {
        createTime: null,
        message: "",
        messageReciver: "",
        messageSender: "",
        status: 2,
      },
      createTime: null,
      // 表单校验
      rules: {
      },
      deptName: "",
      ReciverDisabled: false
    };
  },
  created() {


    const User = localStorage.getItem('User');
    this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';

    if (this.deptName !== '物资公司') {
      this.queryParams.messageReciver = this.deptName;
    } else {
      this.queryParams.messageReciver = "物资公司";
    }
    this.getList();
  },
  methods: {
    /** 查询公告通知列表 */
    getList() {
      if (this.activeName === 'first') {
        // 接收列表
        this.provideShow = false
        this.queryParams.messageSender = "";
        const User = localStorage.getItem('User');
        this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';

        if (this.deptName !== '物资公司') {
          this.queryParams.messageReciver = this.deptName;
        } else {
          this.queryParams.messageReciver = "物资公司";
        }
      } else {
        this.queryParams.messageReciver = "";
        const User = localStorage.getItem('User');
        this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
        if (this.deptName !== '物资公司') {
          this.queryParams.messageSender = this.deptName;

        } else {
          this.queryParams.messageSender = '物资公司'
        }

      }

      if (this.dateTime && this.dateTime.length === 2) {
        // 日期格式转换
        this.queryParams.startTime = this.dateTime[0];
        this.queryParams.endTime = this.dateTime[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
      this.loading = true;
      listMessage(this.queryParams).then(response => {
        this.messageList = response.rows.filter(item => item.status !=='2')
        this.messageList.forEach((item, index) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        messageReciver: null,
        message: null,
        status: null,
        messageSender: null,
        createTime: null,
        readTime: null,
        detailId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateTime = [this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1, 0, 0, 0, 0)), this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 23, 59, 59, 999))];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.ReciverDisabled = false;
      this.createTime = this.formatDate(new Date());
      this.form.createTime = this.createTime;
      this.open = true;
      this.title = "添加公告通知";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.createTime = this.formatDate(new Date());
      this.form.createTime = this.createTime;
      this.ReciverDisabled = true;
      getMessage(id).then(response => {
        this.form = response.data;
        if (this.form.messageReciver === 'ALL') {
          this.form.messageReciver = "全体用户"
        }

        this.open = true;
        this.title = "修改公告通知";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.form.id != null) {
            updateMessage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const User = localStorage.getItem('User');
            this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';

            if (this.deptName !== '物资公司') {
              this.form.messageSender = this.deptName;
            } else {
              this.form.messageSender = "物资公司";
            }
            this.form.status = "0";
            addMessage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除此条公告信息？').then(function () {
        return delMessage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/message/export', {
        ...this.queryParams
      }, `message_${new Date().getTime()}.xlsx`)
    },
    // 日期转换
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleClick(tab, event) {
      this.getList();
    }
  }
};
</script>
